<template>
  <div>
    <div class="form-box">
      <div class="title">收货人</div>
      <input
        placeholder="请输入收货人"
        v-model="createForm.name"
        placeholder-class="placeholderStyle"
      />
    </div>

    <div class="form-box">
      <div class="title">手机号码</div>
      <input
        type="number"
        placeholder="请输入手机号码"
        maxlength="11"
        v-model="createForm.phone"
        placeholder-class="placeholderStyle"
      />
    </div>
    <div class="form-box">
      <div class="title">区域选择</div>
      <picker mode="region" @change="regionChange">
        <text v-if="createForm.region">{{ String(createForm.region) }}</text>
        <text v-else>选择省、市、区</text>
      </picker>
    </div>
    <div class="form-box">
      <div class="title">详细</div>
      <input
        placeholder="请输入详细"
        v-model="createForm.detail"
        placeholder-class="placeholderStyle"
      />
    </div>
    <div class="form-box label flex between">
      <div class="title">标签</div>
      <div class="flex end">
        <template v-for="(item, index) in labels" :key="index">
          <div
            @click="selectLabel(item)"
            class="lb-item"
            :class="item === createForm.label ? 'active' : ''"
            :style="toLabelStyle(item)"
          >
            {{ item }}
          </div>
        </template>
      </div>
    </div>
    <div class="form-box switch">
      <div class="title">设置默认地址</div>
      <switch
        @change="switchChange"
        :checked="createForm.is_default"
        :color="DIYTHEME?.host_bg"
      ></switch>
    </div>

    <hover>
      <div class="save-box fixed" @click="toSave">
        <div
          class="save-btn"
          :style="{
            background: DIYTHEME?.host_bg,
            color: DIYTHEME?.host_color,
          }"
          :disabled="disabledVisblie"
        >
          保存
        </div>
      </div>
    </hover>
  </div>
</template>
<script setup lang="ts">
import { createUserAddress, updateUserAddress,getUserAddressDetail } from "@/api/user-address";
import { useConfig } from "@/store";
import { diyThemeDataType, Result, ResultError } from "@/types";
import { onLoad } from "@dcloudio/uni-app";
import { storeToRefs } from "pinia";
import { ref, getCurrentInstance} from "vue";

const { DIYTHEME } = storeToRefs(useConfig());

const {
  proxy: { $utils },
} = getCurrentInstance() as any;

const createForm = ref<{
  name: string;
  phone: string;
  region: string[];
  detail: string;
  label: string;
  is_default: number | string;
}>({
  name: "",
  phone: "",
  region: ["广东省", "湛江市", "赤坎区"],
  detail: "",
  label: "其他",
  is_default: 0,
});

const labels = ref<string[]>(["公司", "学校", "家", "其他"]);
/**
 * 修改地区
 */
const regionChange = (e: any) => {
  createForm.value.region = e.detail.value;
};

const switchChange = (e: any) => {
  createForm.value.is_default = e.detail.value ? 1 : 0;
};
const selectLabel = (val: string) => {
  createForm.value.label = val;
};

const disabledVisblie = ref<boolean>(false);

const toSave = () => {
  if (!validation()) {
    $utils.errorMsg(errorMsg.value);
    return false;
  }
  if (disabledVisblie.value) {
    return false;
  }
  disabledVisblie.value = true;

  let operationApi: any = null;
  if (!addressId.value) {
    operationApi = createUserAddress(createForm.value);
  } else {
    operationApi = updateUserAddress(
      Object.assign(
        {
          id: addressId.value,
        },
        createForm.value
      )
    );
  }

  operationApi.then((res: Result) => {
      $utils.successMsg(res.message);
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    })
    .catch((err: ResultError) => {
      disabledVisblie.value = false;
      $utils.errorMsg(err);
    });
};

const errorMsg = ref<string>("");
/**
 * 表单验证
 */
const validation = () => {
  if (createForm.value.name === "") {
    errorMsg.value = "收件人不能为空";
    return false;
  }
  if (createForm.value.phone.length < 1) {
    errorMsg.value = "手机号不能为空";
    return false;
  }
  if (createForm.value.phone.length !== 11) {
    errorMsg.value = "手机号长度有误";
    return false;
  }
  let reg = /^((0\d{2,3}-\d{7,8})|(1[3456789]\d{9}))$/;
  if (!reg.test(createForm.value.phone)) {
    errorMsg.value = "手机号无效";
    return false;
  }
  if (!createForm.value.region) {
    errorMsg.value = "省市区不能空";
    return false;
  }
  if (createForm.value.detail === "") {
    errorMsg.value = "详细地址不能为空";
    return false;
  }
  return true;
};

const toLabelStyle = (item: string) => {
  var style: any = {
    background: "#f0f0f0",
    color: "#000000",
  };
  if (item === createForm.value.label) {
    style = {
      background: DIYTHEME.value?.host_bg || style.background,
      borderColor: DIYTHEME.value?.host_bg || style.color,
      color: DIYTHEME.value?.host_color || style.color,
    };
  }
  return style;
};

const addressId = ref<number>(0);

const toInit = () => {
  getUserAddressDetail({
    id: addressId.value,
  })
    .then((res: Result) => {
      var address = res.data;
      createForm.value.name = address.name;
      createForm.value.phone = address.phone;
      createForm.value.region = [
        address.region.province,
        address.region.city,
        address.region.region,
      ];
      createForm.value.detail = address.detail;
      createForm.value.label = address.label;
      createForm.value.is_default = address.is_default;
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
    });
};

onLoad(
  (
    options: {
      id?: number;
    } = {}
  ) => {
    if (options.id) {
      addressId.value = options.id;
      uni.setNavigationBarTitle({
        title: "编辑地址",
      });
      toInit();
    }
  }
);
</script>


<style scoped>
.form-box {
  height: 80rpx;
  line-height: 80rpx;
  width: calc(100% - 60rpx);
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #f9f9f9;
  background: #fff;
  display: flex;
  align-items: center;
}
.form-box .title {
  width: 180rpx;
  height: 80rpx;
  line-height: 80rpx;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  word-break: break-all;
}
.form-box input,
.form-box picker {
  width: calc(100% - 200rpx);
  height: 80rpx;
  line-height: 80rpx;
  color: #000;
}
.form-box.label .lb-item {
  box-sizing: border-box;
  margin-top: 15rpx;
  height: 40rpx;
  line-height: 40rpx;
  border-radius: 40rpx;
  border: 1rpx solid #e0e0e0;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0 18rpx;
  color: #666666;
  font-size: 22rpx;
  margin-right: 14rpx;
}
.form-box.label .active {
  border-width: 1rpx;
  border-style: solid;
  color: #fff;
}

.form-box.switch {
  display: flex;
  justify-content: space-between;
}

.save-btn {
  width: calc(100% - 40rpx);
  margin: 25rpx auto;
  text-align: center;
  height: 80rpx;
  line-height: 80rpx;
  color: #fff;
  border-radius: var(--base-radius-default);
}

.save-box.fixed {
  position: fixed;
  width: 100%;
  height: 120rpx;
  z-index: 9999;
  left: 0rpx;
  bottom: 0rpx;
}
</style>